/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package engine.map;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import mainpackage.Constant;
import mainpackage.GameBean;
import mainpackage.MainCanvas;
import mainpackage.MainLogic;
import mainpackage.ResManager;
import mainpackage.Rms;
import mainpackage.Tools;
import ui.UiInterFace;

/**
 *
 * @author Administrator
 */
public class Map {
    //是否适用缓冲算法
    //第三层大图层变成天空层

    public static boolean blUseBufferMap = true;
    //初始化完毕
    public static boolean blHaveInited = false;
    //双缓冲地图
    private static Image imgBufferMapA;
    private static Image imgBufferMapB;
    public static Image imgCurrentMap;
    //缓冲用到的起始坐标
    private int iSourceX = -1, iSourceY = -1;
    //缓冲用到的graphics
    private static Graphics gA, gB;
    //左上点偏移坐标
    public int iMapViewOffsetX, iMapViewOffsetY;
    public int iMapWorldOffsetX, iMapWorldOffsetY;
    //区域偏移行列数
    public short shMapAnchorR, shMapAnchorC;
    //区域偏移行列数
    public short shMapPlayerR, shMapPlayerC;
    //区域偏移坐标
    public int iMapAnchorX, iMapAnchorY;
    //区域偏移缓冲坐标用户同步网络数据
    public short shMapAnchorXBuffer, shMapAnchorYBuffer;
    //地图层数据
    public static int[][] iMapData;
    //天空层数据
    public static byte[][] bySkyData;
    //碰撞层数据
    public static byte[][] byCollisionData;
    //区域宽高
    public static int shAreaW, shAreaH;
    //区域行列数
    public static short shAreaWCount, shAreaHCount;
    public static int iAreaStartxCount, iAreaStartyCount;
    public static int iAreaStartx, iAreaStarty;
    //屏幕宽高
    public byte byWidth, byHeight;
    //宽高
    public byte byTileW, byTileH;
    //地图图块数据容器
//    public static Hashtable imgMapPool;
    //第一层图块数量
    private int ilayer1TileCount;
    private int ilayer0TileCount;
    private int ilayer2TileCount;
    private int ilayer3TileCount;
    private int ilayer4TileCount;
    private int iborderTileCount;
    public static int iblockXCount;
    public static int iblockYCount;

    public Map() {
        this.byTileW = 16;
        this.byTileH = 16;
        this.byWidth = Constant.SCREEN_WIDTH / 16 + 1;
        this.byHeight = Constant.SCREEN_HEIGHT / 16 + 1;
        blHaveInited = false;
//        if (this.blUseBufferMap) {
//            this.imgBufferMapA = Image.createImage(Constant.SCREEN_WIDTH,
//                    Constant.SCREEN_HEIGHT);
//            this.imgBufferMapB = Image.createImage(Constant.SCREEN_WIDTH,
//                    Constant.SCREEN_HEIGHT);
//            this.gA = this.imgBufferMapA.getGraphics();
//            this.gB = this.imgBufferMapB.getGraphics();
//        }
    }

    public void initMap(DataInputStream streamIn) {
        try {
            byte[] saveArray = new byte[streamIn.available()];
            streamIn.read(saveArray, 0, saveArray.length);
            Rms.saveGame(Constant.RMS_MAP_TER_DATA, saveArray);
            Rms.loadGame(Constant.RMS_MAP_TER_DATA);
            streamIn.close();
            streamIn = null;
        } catch (Exception e) {
            if (Constant.DEBUG) {
                e.printStackTrace();
            }
        }
    }

    public void initMapData(DataInputStream streamIn, boolean blSendimg) {
        try {
//          DataInputStream aInputStream =  (DataInputStream)(streamIn.close());
            int m_resId;
            //资源id
            int m_posX;		 //x
            int m_posY;		 //y
            int m_rot;		 //旋转
            int m_color;         //颜色
            int m_resId2;	 //资源id2
            int m_resId3;	 //资源id3

            //////////////////临时模拟网络数据//////////////////////////////////
//            streamIn = new DataInputStream(getClass().getResourceAsStream("/res/Images/beijianggaoyuan 0 1.ter"));
            //////////////////////////////////////////////////////////////////
            //起始坐标
            iAreaStartx = streamIn.readInt();
            iAreaStarty = streamIn.readInt();
            iAreaStartxCount = iAreaStartx >> 4;
            iAreaStartyCount = iAreaStarty >> 4;
            //关卡宽高
            shAreaW = streamIn.readUnsignedShort();
            shAreaH = streamIn.readUnsignedShort();
            shAreaWCount = (short) (shAreaW >> 4);
            shAreaHCount = (short) (shAreaH >> 4);
            Tools.printLog("地图宽：" + shAreaWCount);
            Tools.printLog("地图高：" + shAreaHCount);
//            更新区域地图坐标MainLogic.gameMap.iMapWorldOffsetX, MainLogic.gameMap.iMapWorldOffsetY
            this.updateMapXy(iAreaStartx, iAreaStarty);
            ilayer0TileCount = streamIn.readUnsignedShort();
            Tools.printLog("ilayer0TileCount：" + ilayer0TileCount);
            if (this.iMapData == null) {
                this.iMapData = new int[7][];
            }
            iMapData[0] = new int[ilayer0TileCount * 6];
            //0层tile
            int j = 0;
            for (int i = 0; i < ilayer0TileCount; i++) {
                m_resId = streamIn.readUnsignedShort();
//                 System.out.print("" +m_resId);
//                m_posX = streamIn.readInt();
//                m_posY = streamIn.readInt();
                m_rot = streamIn.readUnsignedByte();
//                m_resId2 = streamIn.readUnsignedShort();
//                m_resId3 = streamIn.readUnsignedShort();
                {
                    iMapData[0][j] = m_resId;
                    iMapData[0][j + 1] = -1;//m_posX;
                    iMapData[0][j + 2] = -1;// m_posY;
                    iMapData[0][j + 3] = -1;//m_resId2;
                    iMapData[0][j + 4] = -1;//m_resId3;
                    iMapData[0][j + 5] = m_rot;
                    j += 6;
                }
            }
//              Tools.printLog("");
            //1层tile大图层
            ilayer1TileCount = streamIn.readUnsignedShort();
            Tools.printLog("ilayer1TileCount：" + ilayer1TileCount);
            iMapData[1] = new int[ilayer1TileCount * 6];
            j = 0;
            for (int i = 0; i < ilayer1TileCount; i++) {
                m_resId = streamIn.readUnsignedShort();
                //ceshi 
                m_posX = streamIn.readInt();
                m_posY = streamIn.readInt();
                m_rot = streamIn.readUnsignedByte();
//                m_resId2 = streamIn.readUnsignedShort();
//                m_resId3 = streamIn.readUnsignedShort();
                iMapData[1][j] = m_resId;
                iMapData[1][j + 1] = m_posX;
                iMapData[1][j + 2] = m_posY;
                iMapData[1][j + 3] = -1;//m_resId2;
                iMapData[1][j + 4] = -1;//m_resId3;
                iMapData[1][j + 5] = m_rot;
                j += 6;
            }
            //添加的两层
            //2层tile大图层
            ilayer2TileCount = streamIn.readUnsignedShort();
            iMapData[2] = new int[ilayer2TileCount * 6];
            j = 0;
            Tools.printLog("地三层地图：");
            for (int i = 0; i < ilayer2TileCount; i++) {
                m_resId = streamIn.readUnsignedShort();
                Tools.printLog("m_resId：" + m_resId);
                m_posX = streamIn.readInt();
                m_posY = streamIn.readInt();
                m_rot = streamIn.readUnsignedByte();
//                m_resId2 = streamIn.readUnsignedShort();
//                m_resId3 = streamIn.readUnsignedShort();
                iMapData[2][j] = m_resId;
                iMapData[2][j + 1] = m_posX;
                iMapData[2][j + 2] = m_posY;
                iMapData[2][j + 3] = -1;//m_resId2;
                iMapData[2][j + 4] = -1;//m_resId3;
                iMapData[2][j + 5] = m_rot;
                j += 6;
            }
            //3层tile大图层
            ilayer3TileCount = streamIn.readUnsignedShort();
            Tools.printLog("地五层地图：");
            iMapData[6] = new int[ilayer3TileCount * 6];
            j = 0;
            for (int i = 0; i < ilayer3TileCount; i++) {
                m_resId = streamIn.readUnsignedShort();
                Tools.printLog("m_resId：" + m_resId);
                m_posX = streamIn.readInt();
                m_posY = streamIn.readInt();
                m_rot = streamIn.readUnsignedByte();
//                m_resId2 = streamIn.readUnsignedShort();
//                m_resId3 = streamIn.readUnsignedShort();
                iMapData[6][j] = m_resId;
                iMapData[6][j + 1] = m_posX;
                iMapData[6][j + 2] = m_posY;
                iMapData[6][j + 3] = -1;//m_resId2;
                iMapData[6][j + 4] = -1;//m_resId3;
                iMapData[6][j + 5] = m_rot;
                j += 6;
            }
            Tools.printLog("地四层地图：");
            //3层tile大图层
            ilayer3TileCount = streamIn.readUnsignedShort();
            iMapData[3] = new int[ilayer3TileCount * 6];
            j = 0;
            for (int i = 0; i < ilayer3TileCount; i++) {
                m_resId = streamIn.readUnsignedShort();
                Tools.printLog("m_resId：" + m_resId);
                m_posX = streamIn.readInt();
                m_posY = streamIn.readInt();
                m_rot = streamIn.readUnsignedByte();
//                m_resId2 = streamIn.readUnsignedShort();
//                m_resId3 = streamIn.readUnsignedShort();
                iMapData[3][j] = m_resId;
                iMapData[3][j + 1] = m_posX;
                iMapData[3][j + 2] = m_posY;
                iMapData[3][j + 3] = -1;//m_resId2;
                iMapData[3][j + 4] = -1;//m_resId3;
                iMapData[3][j + 5] = m_rot;
                j += 6;
            }
//            //4层tile天空层
//            ilayer4TileCount = streamIn.readUnsignedShort();
//            Tools.printLog("地六层地图：");
//            iMapData[4] = new int[ilayer4TileCount * 6];
//            j = 0;
//            for (int i = 0; i < ilayer4TileCount; i++) {
//                m_resId = streamIn.readUnsignedShort();
//                Tools.printLog("m_resId：" + m_resId);
//                m_posX = streamIn.readInt();
//                m_posY = streamIn.readInt();
//                m_rot = streamIn.readUnsignedByte();
////                m_resId2 = streamIn.readUnsignedShort();
////                m_resId3 = streamIn.readUnsignedShort();
//                iMapData[4][j] = m_resId;
//                iMapData[4][j + 1] = m_posX;
//                iMapData[4][j + 2] = m_posY;
//                iMapData[4][j + 3] = -1;//m_resId2;
//                iMapData[4][j + 4] = -1;//m_resId3;
//                iMapData[4][j + 5] = m_rot;
////                Tools.printLog("m_resId1：" + m_resId + "m_resId2：" + m_resId2 + "m_resId3：" + m_resId3 + "m_posX:" + m_posX + "m_posY:" + m_posY);
//                j += 6;
//            }

//            //边界：上下左右角 上下左右边
//            iborderTileCount = streamIn.readUnsignedShort();
////            iborderTileCount += 1;
//            iMapData[5] = new int[iborderTileCount * 6];
//            j = 0;
//            //存在问题 ：
//            Tools.printLog("地七层地图：");
//            for (int i = 0; i < iborderTileCount; i++) {
//                m_resId = streamIn.readUnsignedShort();
//                Tools.printLog("m_resId：" + m_resId);
//                m_posX = streamIn.readInt();
//                m_posY = streamIn.readInt();
//                m_rot = streamIn.readUnsignedByte();
////                m_color = streamIn.readInt();
////                m_resId2 = streamIn.readUnsignedShort();
////                m_resId3 = streamIn.readUnsignedShort();
//                iMapData[5][j] = m_resId;
//                iMapData[5][j + 1] = m_posX;
//                iMapData[5][j + 2] = m_posY;
//                iMapData[5][j + 3] = -1;//m_resId2;
//                iMapData[5][j + 4] = -1;//m_resId3;
//                iMapData[5][j + 5] = m_rot;
////                Tools.printLog("No:" + i + "m_resId1：" + m_resId + "m_posX:" + m_posX + "m_posY:" + m_posY + "m_resId2：" + m_resId2 + "m_resId3：" + m_resId3);
//                j += 6;
//            }
            //占地各自列数
            iblockXCount = streamIn.readUnsignedShort();
            //占地各自行数0 --- 可走  1--- 不可走  2 --- 转换（待定）
            iblockYCount = streamIn.readUnsignedShort();
            this.byCollisionData = new byte[iblockYCount][iblockXCount];
//            System.out.print("find  tag points start");
            for (int i = 0; i < iblockYCount; i++) {
//                 System.out.println("");
                for (int k = 0; k < iblockXCount; k++) {
                    this.byCollisionData[i][k] = streamIn.readByte();
//                    System.out.print("" + this.byCollisionData[i][k]);
//                    if(this.byCollisionData[i][k] == 2)
//                    System.out.print("find a tag point" + Map.byCollisionData[i][k]);
                }
            }
//            System.out.print("find  tag points end");
            //偏移
//            long lblockOffset = streamIn.readLong();
            //地图图片资源数量先读取小图
            int iimagesIdCount = streamIn.readUnsignedShort();
            //读 ID 存储图片资源
            int[] iResCount = new int[iimagesIdCount];
            for (int i = 0; i < iimagesIdCount; i++) {
                m_resId = streamIn.readInt();
                iResCount[i] = m_resId;
            }
            String[] mapres = checkMapRes(iResCount, true, Constant.RES_TYPE_IMAGE);
            boolean blsend = false;
            if (mapres == null) {
                blsend = true;
//                MainLogic.blLogined = true;
//
//                MainLogic.gameMap.initOffSetXY(MainLogic.getInstance().gamePlayer.iPlayerX, MainLogic.getInstance().gamePlayer.iPlayerY);
////                MainLogic.pushState(Constant.GAME_UI_RAOM, true);
            } else {
//                 MainCanvas.strLoadingNOte = "请求基础层地图";
                MainLogic.gameMap.initOffSetXY(MainLogic.getInstance().gamePlayer.iPlayerX, MainLogic.getInstance().gamePlayer.iPlayerY);
                MainLogic.netController.setMsgResArray(mapres);
                GameBean.SH_RES_PARAMETER_ONE = Constant.RES_PUBLIC_ONEROOM;
                MainLogic.netController.send(Constant.MSG_NET_GET_IMAGE, Constant.SOCKET_MSG_TYPE_RES);
                mapres = null;
            }
            //地图图片资源数量先读取大图
            iimagesIdCount = streamIn.readUnsignedShort();
            //读 ID 存储图片资源
            iResCount = new int[iimagesIdCount];
            for (int i = 0; i < iimagesIdCount; i++) {
                m_resId = streamIn.readInt();
                Tools.printLog("ID:" + m_resId);
                iResCount[i] = m_resId;
            }
            mapres = checkMapRes(iResCount, true, Constant.RES_TYPE_IMAGE);
            if (mapres == null) {
                Tools.printLog("地图大图没有");
//                MainLogic.blLogined = true;
//                UiInterFace.byMaxLoadingNum = (byte) 100;
//                MainLogic.gameMap.initOffSetXY(MainLogic.getInstance().gamePlayer.iPlayerX, MainLogic.getInstance().gamePlayer.iPlayerY);
//                MainLogic.pushState(Constant.GAME_UI_RAOM, true);
            } else {
//                 MainCanvas.strLoadingNOte = "开始申请地图大图";
                Tools.printLog("开始申请地图大图" + mapres.length);
                MainLogic.netController.setMsgResArray(mapres);
                GameBean.SH_RES_PARAMETER_ONE = Constant.RES_PUBLIC_ONEROOM;
                GameBean.SH_RES_PARAMETER_TWO = Constant.NET_TYPE_MAP_IMAGE_2;
                MainLogic.netController.send(Constant.MSG_NET_GET_IMAGE, Constant.SOCKET_MSG_TYPE_RES);
                mapres = null;
            }
            //npc图片ID
            int inpcImgIdCount = streamIn.readUnsignedShort();
//            if (MainLogic.getInstance().gameNpcArray.strNpcResImgIdBuf == null) {
            if (inpcImgIdCount > 0) {
                iResCount = new int[inpcImgIdCount];
                for (int i = 0; i < inpcImgIdCount; i++) {
                    iResCount[i] = streamIn.readInt();

                }
                MainLogic.getInstance().gameNpcArray.strNpcResImgIdBuf = checkMapRes(iResCount, true, Constant.RES_TYPE_NPC_IMAGE);
            }
            //动画资源数量
            int ianiIdCount = streamIn.readUnsignedShort();
//            if (MainLogic.getInstance().gameNpcArray.strNpcResAniIdBuf == null) {
            if (ianiIdCount > 0) {
                iResCount = new int[ianiIdCount];
                Tools.printLog("地图中ianiIdCount：" + ianiIdCount);
                for (int i = 0; i < ianiIdCount; i++) {
                    iResCount[i] = streamIn.readInt();
                    Tools.printLog("iResCount[i]：" + iResCount[i]);
                }
                MainLogic.getInstance().gameNpcArray.strNpcResAniIdBuf = checkMapRes(iResCount, true, Constant.RES_TYPE_ANI);
            }
            if (inpcImgIdCount > 0 && blsend) {
                MainLogic.netController.setMsgResArray(MainLogic.getInstance().gameNpcArray.strNpcResImgIdBuf);
                GameBean.SH_RES_PARAMETER_ONE = Constant.RES_PUBLIC_ONEROOM;
                GameBean.SH_RES_PARAMETER_TWO = Constant.NET_TYPE_NPC_IMAGE;
                MainLogic.netController.send(Constant.MSG_NET_GET_IMAGE, Constant.SOCKET_MSG_TYPE_RES);
            }
//            else
//                if (ianiIdCount > 0) {
//                GameBean.SH_RES_PARAMETER_ONE = Constant.RES_PUBLIC_ONEROOM;
//                GameBean.SH_RES_PARAMETER_TWO = Constant.NET_TYPE_GET_NPC_ANIMATION;
//                MainLogic.netController.setMsgResArray(MainLogic.getInstance().gameNpcArray.strNpcResAniIdBuf);
//                MainLogic.netController.send(Constant.MSG_NET_GET_ANIMATION, Constant.SOCKET_MSG_TYPE_RES);
//            } //本地都存储了
//            else 
            if ((MainLogic.getInstance().gameNpcArray.strNpcResAniIdBuf == null || MainLogic.getInstance().gameNpcArray.strNpcResAniIdBuf.length == 0) && ((MainLogic.getInstance().gameNpcArray.strNpcResImgIdBuf == null || MainLogic.getInstance().gameNpcArray.strNpcResImgIdBuf.length == 0))) {
                MainLogic.getInstance().gameNpcArray.loadNpcRes();
            }
            blHaveInited = true;
            iResCount = null;
            System.gc();
        } catch (Exception e) {
            if (Constant.DEBUG) {
                e.printStackTrace();
            }
        }
    }

    public static void clearMap() {
        blHaveInited = false;
        //地图层数据
        iMapData = null;
        //天空层数据
        bySkyData = null;
        //碰撞层数据
        byCollisionData = null;
        imgCurrentMap = null;
        //地图图块数据容器
        imgBufferMapA = null;
        imgBufferMapB = null;
        gA = null;
        gB = null;
    }

    public String[] checkMapRes(int[] iImgid, boolean blCheckLocal, byte type) {
        Image img = null;
        int index = 0;
        int lengthImgId = 0;
        String[] requestImg = null;
        String[] tempastr = null;
        //寻找本地图片资源
        if (blCheckLocal) {
            //读取img打包文件索引列表
            lengthImgId = iImgid.length - 1;
            requestImg = new String[iImgid.length];
            for (int i = lengthImgId; i >= 0; i--) {
                //找到本地资源
                if (type == Constant.RES_TYPE_IMAGE) {
                    if (ResManager.createImage(iImgid[i], Constant.RES_PUBLIC_ONEROOM, Constant.RES_PATH, false, 9999) == null && iImgid[i] != 0) {
                        requestImg[index] = String.valueOf(iImgid[i]);
                        index++;
                    }
                } else if (type == Constant.RES_TYPE_NPC_IMAGE) {
                    if (ResManager.createImage(iImgid[i], Constant.RES_PUBLIC_ONEROOM, Constant.RES_PATH, false, -1) == null && iImgid[i] != 0) {
                        requestImg[index] = String.valueOf(iImgid[i]);
                        index++;
                    }
                } else {
                    if (ResManager.loadAnimation(iImgid[i], Constant.RES_PUBLIC_ONEROOM, false) == null && iImgid[i] != 0) {
                        requestImg[index] = String.valueOf(iImgid[i]);
                        index++;
                    }
                }
            }
            if (index > 0) {
                tempastr = new String[index];
                System.arraycopy(requestImg, 0, tempastr, 0, tempastr.length);
            }
        }
        requestImg = null;
        if (tempastr != null && blCheckLocal && index > 0) {
            return tempastr;
        } else {
            return null;
        }
    }

    /*
     * 单缓冲卡马克
     */
    /** 缓冲区增大的大小（上下大小是一样的） */
    private static int buffSize;
    /** 缓冲区宽高，命名方式为：Carmack width or height */
    /** 缓冲区宽的图块数，与高的图块数，命名方式为：Carmack title width or height num*/
    private static int carTitleWidthNum, carTitleHeightNum;
    /** 缓冲切割线，命名方式为：Carmack x or y */
    private int carx, cary;
    /** 地图在缓冲区的X 、Y偏移量，命名方式为：map offset x or y */
    private int mapOffx, mapOffy;
    private int mapStartx, mapStarty;
    private int mapStartCol, mapStartRow;
    //////////////////////////////////////////////////////
    private short swWidth, swHeight;                //屏幕尺寸
    private byte stage;                            //关卡数
    private byte dir;                              //滚动方向(0:up 1:right)
    private short mapRows, mapCols;                 //地图块尺寸
    public static int mapWidth, mapHeight;        //地图尺寸
    private byte layerCnt;                         //地图层数
//    private byte backLayerCnt;                     //背景层数
    private byte[][][] Layers;                     //地图网格数组
    private byte[][] TileType;                     //地图块类型 
    private int lcdx, lcdy;                       //屏幕左上角坐标
    private short lcdStartX, lcdStartY;             //屏幕左上角块坐标
    private short bufCols, bufRows;                 //缓存的块尺寸
    private short bufStartX, bufStartY;             //缓存起始块坐标
    private byte mImgCols;                         //块图中共有多少列
    //////////////////////////////
//网格
    public final static byte TILEW = 16;
    public final static byte TILEH = 16;

    private void initBuffS40() {
        //////////////////////////////////////
        swWidth = Constant.SCREEN_WIDTH;
        swHeight = Constant.SCREEN_HEIGHT;
        lcdx = this.iMapViewOffsetX;
        lcdy = this.iMapViewOffsetY;
        mapWidth = shAreaW;
        mapHeight = shAreaH;
        mapRows = shAreaWCount;
        mapCols = shAreaHCount;
        ;
        if (mapWidth > swWidth) {
            bufCols = (short) ((swWidth % TILEW > 0) ? swWidth / TILEW + 2 : swWidth / TILEW + 1);
            bufStartX = (short) (lcdx / TILEW);
        } else {
            bufCols = (short) (swWidth / TILEW);
            bufStartX = (short) (lcdx / TILEW);
        }
        if (mapHeight > swHeight) {
            bufRows = (short) ((swHeight % TILEH > 0) ? swHeight / TILEH + 2 : swHeight / TILEH + 1);
            bufStartY = (short) ((swHeight % TILEH > 0) ? lcdy / TILEH - 2 : lcdy / TILEH - 1);
//             bufStartY = (short) ((lcdy / TILEH > 0) ? lcdy / TILEH - 2 : lcdy / TILEH - 1);
        } else {
            bufRows = (short) (swHeight / TILEH);
            bufStartY = (short) (lcdy / TILEH);
        }
        if (bufStartY < 0) {
            bufStartY = 0;
        }
        if (bufStartX < 0) {
            bufStartX = 0;
        }
        lcdStartX = (short) (lcdx / TILEW);
        lcdStartY = (short) (lcdy / TILEH);
        imgBufferMapA = Image.createImage(bufCols * TILEW, bufRows * TILEH);
        gA = imgBufferMapA.getGraphics();
//        this.drawMapBasicLayer(gA, this.iMapViewOffsetX, this.iMapViewOffsetY, bufCols*TILEW, bufRows*TILEH);
        initBuffer(gA);
    }
    //初始化缓存

    public void resetBuffer() {
        lcdx = this.iMapViewOffsetX;
        lcdy = this.iMapViewOffsetY;
        if (mapWidth > swWidth) {
            bufCols = (short) ((swWidth % TILEW > 0) ? swWidth / TILEW + 2 : swWidth / TILEW + 1);
            bufStartX = (short) (lcdx / TILEW);
        } else {
            bufCols = (short) (swWidth / TILEW);
            bufStartX = (short) (lcdx / TILEW);
        }
        if (mapHeight > swHeight) {
            bufRows = (short) ((swHeight % TILEH > 0) ? swHeight / TILEH + 2 : swHeight / TILEH + 1);
            bufStartY = (short) ((swHeight % TILEH > 0) ? lcdy / TILEH - 2 : lcdy / TILEH - 1);
//             bufStartY = (short) ((lcdy / TILEH > 0) ? lcdy / TILEH - 2 : lcdy / TILEH - 1);
        } else {
            bufRows = (short) (swHeight / TILEH);
            bufStartY = (short) (lcdy / TILEH);
        }
        if (bufStartY < 0) {
            bufStartY = 0;
        }
        if (bufStartX < 0) {
            bufStartX = 0;
        }
        lcdStartX = (short) (lcdx / TILEW);
        lcdStartY = (short) (lcdy / TILEH);
        initBuffer(gA);
    }

    private void initBuffer(Graphics g) {
        try {
            Image img;
//        for (int k = 0; k < backLayerCnt; k++) 
            {
                for (int i = bufStartX; i < bufStartX + bufCols; i++) {
                    for (int j = bufStartY; j < bufStartY + bufRows; j++) {
                        img = (Image) ResManager.getImage(iMapData[0][(45) * (j) * 6 + (i) * 6], (byte) -1);
//                        System.out.println("id" + iMapData[0][(45) * (j) * 6 + (i) * 6]);
                        if (img != null) {
                            if (this.iMapData[0][(45) * (j) * 6 + (i) * 6 + 5] == 0) {
                                gA.drawImage(img, (i % bufCols) * TILEW, (j % bufRows) * TILEH, Graphics.LEFT | Graphics.TOP);
                            } else {
                                Tools.drawRegion(img, 0, 0, 16, 16, this.iMapData[0][(45) * (j) * 6 + (i) * 6 + 5], (i % bufCols) * TILEW, (j % bufRows) * TILEH, Graphics.LEFT | Graphics.TOP, gA);
                            }
                        }
                    }
                }
            }
            img = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
//更新缓存

    private void updateBuffer(Graphics g) {
        try {
            lcdx = this.iMapViewOffsetX;
            lcdy = this.iMapViewOffsetY;
            lcdStartX = (short) (lcdx / TILEW);
            lcdStartY = (short) (lcdy / TILEH);
            Image img;
            //更新左边界
            if (lcdStartX < bufStartX) {
                for (int j = bufStartY; j < bufStartY + bufRows; j++) {
                    img = (Image) ResManager.getImage(this.iMapData[0][(45) * j * 6 + (lcdStartX) * 6], (byte) -1);
                    if (img != null) {
                        if (this.iMapData[0][(45) * (j) * 6 + (lcdStartX) * 6 + 5] == 0) {
                            gA.drawImage(img, (lcdStartX % bufCols) * TILEW, (j % bufRows) * TILEH, 20);
                        } else {
                            Tools.drawRegion(img, 0, 0, 16, 16, this.iMapData[0][(45) * (j) * 6 + (lcdStartX) * 6 + 5], (lcdStartX % bufCols) * TILEW, (j % bufRows) * TILEH, 20, gA);
                        }
                    }
                }
                bufStartX = lcdStartX;
            } //更新右边界
            else if (lcdStartX > bufStartX && (bufStartX % mapCols < mapCols - bufCols)) {
//			for (int k = 0 ; k < backLayerCnt ; k++)
                {
                    for (int j = bufStartY; j < bufStartY + bufRows; j++) {
                        img = (Image) ResManager.getImage(this.iMapData[0][(45) * (j) * 6 + (lcdStartX + bufCols - 1) * 6], (byte) -1);
                        if (img != null) {
                            if (this.iMapData[0][(45) * (j) * 6 + (lcdStartX + bufCols - 1) * 6 + 5] == 0) {
                                gA.drawImage(img, ((lcdStartX + bufCols - 1) % bufCols) * TILEW, (j % bufRows) * TILEH, 20);
                            } else {
                                Tools.drawRegion(img, 0, 0, 16, 16, this.iMapData[0][(45) * (j) * 6 + (lcdStartX + bufCols - 1) * 6 + 5], ((lcdStartX + bufCols - 1) % bufCols) * TILEW, (j % bufRows) * TILEH, 20, gA);
                            }
                        }
                    }
                }
                bufStartX = lcdStartX;
            }

            //更新上边界
            if (lcdStartY < bufStartY) {
//			for (int k = 0 ; k < backLayerCnt ; k++)
                {
                    for (int i = bufStartX; i < bufStartX + bufCols; i++) {
                        img = (Image) ResManager.getImage(this.iMapData[0][(45) * lcdStartY * 6 + (i) * 6], (byte) -1);
                        if (img != null) {
                            if (this.iMapData[0][(45) * (lcdStartY) * 6 + (i) * 6 + 5] == 0) {
                                gA.drawImage(img, (i % bufCols) * TILEW, (lcdStartY % bufRows) * TILEH, 20);
                            } else {
                                Tools.drawRegion(img, 0, 0, 16, 16, this.iMapData[0][(45) * (lcdStartY) * 6 + (i) * 6 + 5], (i % bufCols) * TILEW, (lcdStartY % bufRows) * TILEH, 20, gA);
                            }
                        }
                    }
                }
                bufStartY = lcdStartY;
            } //更新下边界
            else if (lcdStartY > bufStartY) {//&& (bufStartY)< mapRows - bufRows) {
//            for (int k = 0; k < backLayerCnt; k++)
                {
                    for (int i = bufStartX; i < bufStartX + bufCols; i++) {
                        img = (Image) ResManager.getImage(Map.iMapData[0][(45) * (lcdStartY + bufRows - 1) * 6 + (i) * 6], (byte) -1);
                        if (img != null) {
                            if (this.iMapData[0][(45) * (lcdStartY + bufRows - 1) * 6 + (i) * 6 + 5] == 0) {
                                gA.drawImage(img, (i % bufCols) * TILEW, ((lcdStartY + bufRows - 1) % bufRows) * TILEH, 20);
                            } else {
                                Tools.drawRegion(img, 0, 0, 16, 16, this.iMapData[0][(45) * (lcdStartY + bufRows - 1) * 6 + (i) * 6 + 5], (i % bufCols) * TILEW, ((lcdStartY + bufRows - 1) % bufRows) * TILEH, 20, gA);
                            }
                        }
                    }
                }
                bufStartY = lcdStartY;
            }
            img = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
//**功能函数
//////////////////////////////////////////////////////

    //绘制剪切图
    private void drawClipImage(Graphics g, Image img, int tx, int ty, int tw, int th, int x, int y) {
        g.setClip(x, y, tw, th);
        g.drawImage(img, x - tx, y - ty, 0);
        g.setClip(0, 0, swWidth, swHeight);
    }

    private void drawWithDoubleBufferS40(Graphics g) {
        if (imgBufferMapA == null) {
            initBuffS40();
//            MainCanvas.backGraphics.drawImage(imgBufferMapA, 0, 0, 0);
        }
//        else 
        {
            drawBackMap(MainCanvas.backGraphics);
        }
        this.drawBigLayer(MainCanvas.backGraphics, this.iMapViewOffsetX, this.iMapViewOffsetY, Constant.SCREEN_WIDTH, Constant.SCREEN_HEIGHT);
    }
    //绘制底层地图

    public void drawBackMap(Graphics g) {

        int offx = lcdx % TILEW;
        int offy = lcdy % TILEH;
        if (lcdStartX > bufStartX) {
            offx += TILEW;
        }
        if (lcdStartY > bufStartY) {
            offy += TILEH;
        }
        int x = bufStartX % bufCols;
        int y = bufStartY % bufRows;

        //左上位置为buffer的右下块
        g.setClip(-offx + 0, -offy + 0, (bufCols - x) * TILEW, (bufRows - y) * TILEH);
        g.drawImage(imgBufferMapA, -offx + 0 - x * TILEW, -offy + 0 - y * TILEH, 0);
        //右下位置为buffer的左上块
        g.setClip(-offx + (bufCols - x) * TILEW, -offy + (bufRows - y) * TILEH, x * TILEW, y * TILEH);
        g.drawImage(imgBufferMapA, -offx + (bufCols - x) * TILEW, -offy + (bufRows - y) * TILEH, 0);
        //右上位置为buffer的左下块
        g.setClip(-offx + (bufCols - x) * TILEW, -offy + 0, x * TILEW, (bufRows - y) * TILEH);
        g.drawImage(imgBufferMapA, -offx + (bufCols - x) * TILEW, -offy + 0 - y * TILEH, 0);
        //左下位置为buffer的右上块
        g.setClip(-offx + 0, -offy + (bufRows - y) * TILEH, (bufCols - x) * TILEW, y * TILEH);
        g.drawImage(imgBufferMapA, -offx + 0 - x * TILEW, -offy + (bufRows - y) * TILEH, 0);
        g.setClip(0, 0, swWidth, swHeight);

    }

    /**
     * 卷轴滚动
     *
     * @param x
     *            X轴滚动
     * @param y
     *            Y轴滚动
     */
    public void scroll(int x, int y) {
        if (blUseBufferMap) {
            updateBuffer(gA);
        }
//        if (y > 0) 

//        if(x < -carWidth)
//        {
//          mapOffx = 0;
//            return;  
//        }

//        if (y > shAreaH) {
//            mapOffy = shAreaH;
//            return;
//        }

    }

    /**
     * 画图
     *
     * @param g
     *            目标屏幕的画笔
     * @param img
     *            原图片
     * @param x_src
     *            原图片X坐标
     * @param y_src
     *            原图片Y坐标
     * @param width
     *            原图片宽度
     * @param height
     *            原图片高度
     * @param transform
     *            旋转角度
     * @param x_dest
     *            目标屏幕的X坐标
     * @param y_dest
     *            目标屏幕的Y坐标
     * @param anchor
     *            画笔的锚点
     */
    private void drawRegion(Graphics g, Image img, int x_src, int y_src,
            int width, int height, int transform, int x_dest,
            int y_dest,
            int anchor) {
        // 作宽度检测
        if (width <= 0 || height <= 0) {
            return;
        }
        // 作超屏幕宽度检测
        if (width > Constant.SCREEN_WIDTH) {
            width = Constant.SCREEN_WIDTH;
            // 作超屏幕高度检测
        }
        if (height > Constant.SCREEN_HEIGHT) {
            height = Constant.SCREEN_HEIGHT;
        }
        g.drawRegion(img, x_src, y_src, width, height, transform, x_dest,
                y_dest, anchor);
    }
//
//    private void updateBuffer(int x, int y, int type) {
////        this.iMapViewOffsetX, this.iMapViewOffsetY
////              lcdStartX = (short)(this.iMapViewOffsetX /  Constant.TITLEWIDHT);
////		lcdStartY = (short)( this.iMapViewOffsetY /  Constant.TITLEWIDHT);
//        // 右移
//        gA.setClip(0, 0, carWidth, carHeight);
//        if (type == 0) {
//            if (x > carx + buffSize) {
//                int indexMapLastX = getIndexBuffLastX();
//                System.out.println();
//                if (indexMapLastX < shAreaWCount) {
//                    copyBufferX(indexMapLastX, getIndexCarY(), getTitleHeight(),
//                            getBufferCarX(), getBufferCarY());
//                    carx += Constant.TITLEWIDHT;
//                }
//            }
//            // 左移
//            if (x < carx) {
//                carx -= Constant.TITLEWIDHT;
//                copyBufferX(getIndexCarX(), getIndexCarY(), getTitleHeight(),
//                        getBufferCarX(), getBufferCarY());
//            }
//        } else if (type == 1) {
//            // 下移
//            if (y > cary + buffSize) {
//                int indexMapLastY = getIndexBuffLastY();
//                if (indexMapLastY < shAreaHCount) {
//                    copyBufferY(getIndexCarX(), indexMapLastY, getTitelWidth(),
//                            getBufferCarX(), getBufferCarY());
//                    cary += Constant.TITLEWIDHT;
//                }
//            }
//             if (y < cary)  // 上移
//            {
//                cary -= Constant.TITLEWIDHT;
//                copyBufferY(getIndexCarX(), getIndexCarY(), getTitelWidth(),
//                        getBufferCarX(), getBufferCarY());
//            }
//            System.out.println("y"+y+"cary"+cary);
//        }
//    }

    private void copyBufferX(int indexMapx, int indexMapy, int titleHeight,
            int destx, int desty) {
        int mapImagex, mapImagey, vy;
        // 拷贝地图上面到缓冲的下面
//        System.out.println("mapOffx" + mapOffx + "destx" + destx + "indexMapx" + indexMapx + "indexMapy" + indexMapy);
        Image img;
        for (int j = 0; j < titleHeight; j++) {
            img = (Image) ResManager.getImage(this.iMapData[0][(45) * (indexMapy + j) * 6 + indexMapx * 6], (byte) -1);
            if (img != null) {
//                vy = j * Constant.TITLEWIDHT + desty;
                vy = j * Constant.TITLEWIDHT;
                if (this.iMapData[0][(45) * (indexMapy + j) * 6 + indexMapx * 6 + 5] == 0) {
                    gA.drawImage(img, destx, vy, 20);
                } else {
                    Tools.drawRegion(img, 0, 0, 16, 16, this.iMapData[0][(45) * (indexMapy + j) * 6 + indexMapx * 6 + 5], destx, vy, 20, gA);
                }
            }
        }
        // 拷贝地图下面到缓冲的上面
        for (int k = titleHeight; k < carTitleHeightNum; k++) {
            img = (Image) ResManager.getImage(this.iMapData[0][(45) * (indexMapy + k) * 6 + indexMapx * 6], (byte) -1);
            if (img != null) {
                vy = (k - titleHeight) * Constant.TITLEWIDHT;
                if (this.iMapData[0][(45) * (indexMapy + k) * 6 + indexMapx * 6 + 5] == 0) {
                    gA.drawImage(img, destx, vy, 20);
                } else {
                    Tools.drawRegion(img, 0, 0, 16, 16, this.iMapData[0][(45) * (indexMapy + k) * 6 + indexMapx * 6 + 5], destx, vy, 20, gA);
                }
            }
        }
    }

    private void copyBufferY(int indexMapx, int indexMapy, int titleWidth,
            int destx, int desty) {
        int mapImagex, mapImagey, vx;
//        System.out.println("mapOffy" + mapOffy + "desty" + desty + "indexMapx" + indexMapx + "indexMapy" + indexMapy);
        // 拷贝地图左面到缓冲的右面
        Image img;
        for (int i = 0; i < titleWidth; i++) {
            img = (Image) ResManager.getImage(this.iMapData[0][(45) * (indexMapy) * 6 + (indexMapx + i) * 6], (byte) -1);
            if (img != null) {
//                vx = i * Constant.TITLEWIDHT + destx;
                vx = i * Constant.TITLEWIDHT;
                if (this.iMapData[0][(45) * (indexMapy) * 6 + (indexMapx + i) * 6 + 5] == 0) {
                    gA.drawImage(img, vx, desty, 20);
                } else {
                    Tools.drawRegion(img, 0, 0, 16, 16, this.iMapData[0][(45) * (indexMapy) * 6 + (indexMapx + i) * 6 + 5], vx, desty, 20, gA);
                }
            }
        }
        // 拷贝地图右面到缓冲的左面
        for (int k = titleWidth; k < carTitleWidthNum; k++) {
            img = (Image) ResManager.getImage(this.iMapData[0][(45) * (indexMapy) * 6 + (indexMapx + k) * 6], (byte) -1);
            if (img != null) {
                vx = (k - titleWidth) * Constant.TITLEWIDHT;
                if (this.iMapData[0][(45) * (indexMapy) * 6 + (indexMapx + k) * 6 + 5] == 0) {
                    gA.drawImage(img, vx, desty, 20);
                } else {
                    Tools.drawRegion(img, 0, 0, 16, 16, this.iMapData[0][(45) * (indexMapy) * 6 + (indexMapx + k) * 6 + 5], vx, desty, 20, gA);
                }
            }
        }
    }

    /**
     * 获得切割线所在的索引X
     *
     * @return 索引X
     */
    private int getIndexCarX() {
        return mapStartCol + carx / Constant.TITLEWIDHT;
    }

    /**
     * 获得切割线所在的索引Y
     *
     * @return 索引Y
     */
    private int getIndexCarY() {
        return mapStartRow + cary / Constant.TITLEWIDHT;
    }

    /**
     * 获得切割线在Buffer中的X位置
     *
     * @return 切割线在Buffer中的X位置
     */
    /**
     * 获得缓冲区后面的X索引
     *
     * @return 后面的X索引
     */
    /**
     * 获得当前图块高度的数量
     *
     * @return 当前图块高度的数量
     */
    /**
     */
    private void drawWithDoubleBuffer() {
        if (this.blUseBufferMap && this.imgBufferMapA == null) {

            this.imgBufferMapA = Image.createImage(Constant.SCREEN_WIDTH,
                    Constant.SCREEN_HEIGHT);
            this.imgBufferMapB = Image.createImage(Constant.SCREEN_WIDTH,
                    Constant.SCREEN_HEIGHT);
            this.gA = this.imgBufferMapA.getGraphics();
            this.gB = this.imgBufferMapB.getGraphics();
        }
        if (this.imgCurrentMap == null) {
            this.draw(this.gA, null, this.iMapViewOffsetX, this.iMapViewOffsetY);
            this.imgCurrentMap = imgBufferMapA;
        } else {
            if (this.imgCurrentMap == imgBufferMapA) {
                this.draw(this.gB, imgBufferMapA, this.iMapViewOffsetX, this.iMapViewOffsetY);
                this.imgCurrentMap = imgBufferMapB;
            } else {
                this.draw(this.gA, imgBufferMapB, this.iMapViewOffsetX, this.iMapViewOffsetY);
                this.imgCurrentMap = imgBufferMapA;
            }
        }
        MainCanvas.backGraphics.setClip(0, 0, Constant.SCREEN_WIDTH, Constant.SCREEN_HEIGHT);
        MainCanvas.backGraphics.drawImage(imgCurrentMap, 0, 0, 20);
        MainCanvas.backGraphics.setClip(0, 0, Constant.SCREEN_WIDTH, Constant.SCREEN_HEIGHT);
    }

    /**
     * 绘制地图
     * @param g
     * @param x
     * @param y
     * @param w
     * @param h
     */
    public void drawMap(Graphics g, int x, int y, int w, int h) {
        if (blUseBufferMap) {
            //#if NOKIA_S40V3 || NOKIAN73 || NORMAL_240_400
//#             drawWithDoubleBufferS40(gA);
            //#else
            drawWithDoubleBuffer();
            //#endif

        } else {
            drawMapBasicLayer(g, x, y, w, h);
        }
    }

    /**
     * 绘制地图
     * @param g Graphics 
     * @param sourceImg Image 
     * @param iAimX int 
     * @param iAimY int 
     */
    public void draw(Graphics g, Image sourceImg, int iAimX, int iAimY) {
        if (!blHaveInited) {
            return;
        }
        g.setColor(0x000000);
        g.fillRect(0, 0, Constant.SCREEN_WIDTH, Constant.SCREEN_HEIGHT);
        if (sourceImg == null) {
            this.drawMapBasicLayer(g, iAimX, iAimY, Constant.SCREEN_WIDTH, Constant.SCREEN_HEIGHT);
        } else {
            g.drawImage(sourceImg, this.iSourceX - iAimX, this.iSourceY - iAimY, 20);
            int distanceX = this.iSourceX - iAimX;
            int distanceY = this.iSourceY - iAimY;
            if (distanceX > 0) {
                this.drawMapBasicLayer(g, iAimX, iAimY, distanceX, Constant.SCREEN_HEIGHT);
            } else if (distanceX < 0) {
                this.drawMapBasicLayer(g, Constant.SCREEN_WIDTH + this.iSourceX, iAimY, -distanceX, Constant.SCREEN_HEIGHT);
            }
            if (distanceY > 0) {
                this.drawMapBasicLayer(g, iAimX, iAimY, Constant.SCREEN_WIDTH, distanceY);
            } else if (distanceY < 0) {
                this.drawMapBasicLayer(g, iAimX, Constant.SCREEN_HEIGHT + this.iSourceY, Constant.SCREEN_WIDTH, -distanceY);
            }
        }
        this.iSourceX = iAimX;
        this.iSourceY = iAimY;
    }

    /**
     * 绘制底层地图
     */
    public void drawMapBasicLayerS40(Graphics g, int x, int y, int w, int h, byte type) {
        int startMapViewOffx = 0;//(x %this.byTileW);
        int startMapViewOffy = 0;// (y %this.byTileH);
        int startMapX = (x / this.byTileW);
        int endMapX = ((x + w) / this.byTileW + 1);
        int startMapY = (y / this.byTileH);
        int endMapY = ((y + h) / this.byTileH + 1);
        int offx = 0;
        int offy = 0;
        switch (type) {
            case 0://绘制右边地图到缓冲左边
                offx = -(Constant.SCREEN_WIDTH - w);
                offy = 0;
                break;
            case 1://绘制左边地图到缓冲右边
                offx = Constant.SCREEN_WIDTH - w;
                offy = 0;
                break;
        }
        if (startMapX < 0) {
            startMapX = 0;
        }
        if (endMapX > Constant.AREA_ROWS) {
            endMapX = Constant.AREA_ROWS;
        }
        if (startMapY < 0) {
            startMapY = 0;
        }
        if (endMapY > Constant.AREA_COLUMNS) {
            endMapY = Constant.AREA_COLUMNS;
        }
//        try{
        int viewportX, viewportY;
        Image img = null;
        Image img2 = null;
        viewportY = (startMapY) * this.byTileH - this.iMapViewOffsetY;
        viewportX = (startMapX) * this.byTileW - this.iMapViewOffsetX + startMapViewOffx;
        try {
            for (int mapY = startMapY; mapY < endMapY; mapY++) {
                viewportX = startMapX * this.byTileW - this.iMapViewOffsetX + startMapViewOffx + offx;
                //viewportX = 0;
                for (int mapX = startMapX; mapX < endMapX; mapX++) {
                    try {
                        img = (Image) ResManager.getImage(this.iMapData[0][(45) * (mapY) * 6 + mapX * 6], (byte) -1);
//                            img = (Image) ResManager.getImage("0", (byte) -1);
//                            Tools.printLog(imgMapPool.size());
                        if (img != null) {
                            if (this.iMapData[0][(45) * (mapY) * 6 + mapX * 6 + 5] == 0) {
                                g.drawImage(img, viewportX, viewportY, 20);
                            } else {
                                Tools.drawRegion(img, 0, 0, 16, 16, this.iMapData[0][(45) * (mapY) * 6 + mapX * 6 + 5], viewportX, viewportY, 20, g);
                            }
                        }
                    } catch (Exception e) {
                        if (Constant.DEBUG) {
                            e.printStackTrace();
                        }
                        Tools.printLog("ddd");
                    }

                    viewportX += this.byTileW;
                }
                viewportY += this.byTileH;
            }
//            this.drawBoderMap(g, startMapX / Constant.TITLEWIDHT, startMapY / Constant.TITLEHEIGHT);

//            this.drawBoderMap(g, x, y);
        } catch (Exception e) {
            if (Constant.DEBUG) {
                e.printStackTrace();
            }
            Tools.printLog("地图资源载入失败");
        }
    }

    /**
     * 绘制底层地图
     */
    public void drawMapBasicLayer(Graphics g, int x, int y, int w, int h) {
        int startMapViewOffx = 0;//(x %this.byTileW);
        int startMapViewOffy = 0;// (y %this.byTileH);
        int startMapX = (x / this.byTileW);
        int endMapX = ((x + w) / this.byTileW + 1);
        int startMapY = (y / this.byTileH);
        int endMapY = ((y + h) / this.byTileH + 1);
        if (startMapX < 0) {
            startMapX = 0;
        }
        if (endMapX > Constant.AREA_ROWS) {
            endMapX = Constant.AREA_ROWS;
        }
        if (startMapY < 0) {
            startMapY = 0;
        }
        if (endMapY > Constant.AREA_COLUMNS) {
            endMapY = Constant.AREA_COLUMNS;
        }
//        try{
        int viewportX, viewportY;
        Image img = null;
        Image img2 = null;
        viewportY = (startMapY) * this.byTileH - this.iMapViewOffsetY;
        viewportX = (startMapX) * this.byTileW - this.iMapViewOffsetX + startMapViewOffx;
        try {
            for (int mapY = startMapY; mapY < endMapY; mapY++) {
                viewportX = startMapX * this.byTileW - this.iMapViewOffsetX + startMapViewOffx;
                //viewportX = 0;
                for (int mapX = startMapX; mapX < endMapX; mapX++) {
                    try {
                        img = (Image) ResManager.getImage(this.iMapData[0][(45) * (mapY) * 6 + mapX * 6], (byte) -1);
//                            img = (Image) ResManager.getImage("0", (byte) -1);
//                            Tools.printLog(imgMapPool.size());
                        if (img != null) {
                            if (this.iMapData[0][(45) * (mapY) * 6 + mapX * 6 + 5] == 0) {
                                g.drawImage(img, viewportX, viewportY, 20);
                            } else {
                                Tools.drawRegion(img, 0, 0, 16, 16, this.iMapData[0][(45) * (mapY) * 6 + mapX * 6 + 5], viewportX, viewportY, 20, g);
                            }
                        }
                        //绘制碰撞格子
//                        if (this.byCollisionData[mapY][mapX] != -1)
//                        {
//                            g.setColor(0xff0000);
//                            g.drawRect(viewportX, viewportY, 16, 16);
//                        }
//                        if(this.byCollisionData[mapY][mapX] == 2)
//                        {
//                            g.setColor(0x0000ff);
//                            g.drawRect(viewportX, viewportY, 16, 16);
//                        }
                    } catch (Exception e) {
                        if (Constant.DEBUG) {
                            e.printStackTrace();
                        }
                        Tools.printLog("ddd");
                    }
                    ////////////////////////
//                    if (this.byAfoulData[mapY][mapX] < -1)
//                        {
//                        img2 = (Image) this.imgMapPool.get(String.valueOf(Math.abs(this.byAfoulData[mapY][mapX])));
//                        if (img2 != null)
//                            {
//                            g.drawImage(img2, viewportX, viewportY, 20);
//                            }
//                        }
//                    else if (this.byAfoulData[mapY][mapX] > 1)
//                        { //
//                        img2 = (Image) this.imgMapPool.get(String.valueOf(Math.abs(this.byAfoulData[mapY][mapX])));
//
//                        if (img2 != null)
//                            {
//                            g.drawImage(img2, viewportX, viewportY, 20);
//                            }
//
//                        }

                    viewportX += this.byTileW;
                }
                viewportY += this.byTileH;
            }
//            this.drawBoderMap(g, startMapX / Constant.TITLEWIDHT, startMapY / Constant.TITLEHEIGHT);
            this.drawBigLayer(g, x, y, w, h);
//            this.drawBoderMap(g, x, y);
        } catch (Exception e) {
            if (Constant.DEBUG) {
                e.printStackTrace();
            }
            Tools.printLog("地图资源载入失败");
        }
    }
    /*
     * 判断大图是否在屏幕内
     */

    public boolean bigMapInScreen(int x, int y, int w, int h) {
        int y1 = y + h;//左上点Y
        int x1 = x + w;//左下点X
        if (x >= Constant.SCREEN_WIDTH || x1 <= 0) {
            return false;
        }
        if (y1 <= 0 || y >= Constant.SCREEN_HEIGHT) {
            return false;
        }
        return true;
    }

    /**
     * 绘制大图层
     * @param g
     * @param x
     * @param y
     * @param w
     * @param h
     */
    public void drawBigLayer(Graphics g, int x, int y, int w, int h) {
        try {
            int viewportX, viewportY;
            Image img = null;
            viewportY = this.iMapAnchorY + this.iMapViewOffsetY;
            viewportX = this.iMapAnchorX + this.iMapViewOffsetX;
            int length;
            length = this.iMapData[1].length - 6;
            int imgx, imgy, imgw, imgh;
            g.setClip(0, 0, Constant.SCREEN_WIDTH, Constant.SCREEN_HEIGHT);
            for (int i = length; i >= 0; i -= 6) {
                img = ResManager.getImage(this.iMapData[1][i], (byte) -1);
                if (img != null) {
                    imgx = this.iMapData[1][i + 1] - viewportX;
                    imgy = this.iMapData[1][i + 2] - viewportY;
                    imgw = img.getWidth();
                    imgh = img.getHeight();
                    if (bigMapInScreen(imgx, imgy, imgw, imgh)) {
                        Tools.drawRegion(img, 0, 0, imgw, imgh, this.iMapData[1][i + 5], imgx, imgy, 20, g);
                    }
                }
            }
            //后面添加的两层
            //第二层
            length = this.iMapData[2].length - 6;
            for (int i = length; i >= 0; i -= 6) {
                img = ResManager.getImage(this.iMapData[2][i], (byte) -1);
                if (img != null) {
                    imgx = this.iMapData[2][i + 1] - viewportX;
                    imgy = this.iMapData[2][i + 2] - viewportY;
                    imgw = img.getWidth();
                    imgh = img.getHeight();
                    if (bigMapInScreen(imgx, imgy, imgw, imgh)) {
                        Tools.drawRegion(img, 0, 0, img.getWidth(), img.getHeight(), this.iMapData[2][i + 5], imgx, imgy, 20, g);
                    }
                }
            }
            length = this.iMapData[6].length - 6;
            for (int i = length; i >= 0; i -= 6) {
                img = ResManager.getImage(this.iMapData[6][i], (byte) -1);
                if (img != null) {
                    imgx = this.iMapData[6][i + 1] - viewportX;
                    imgy = this.iMapData[6][i + 2] - viewportY;
                    imgw = img.getWidth();
                    imgh = img.getHeight();
                    if (bigMapInScreen(imgx, imgy, imgw, imgh)) {
                        Tools.drawRegion(img, 0, 0, img.getWidth(), img.getHeight(), this.iMapData[6][i + 5], imgx, imgy, 20, g);
                    }
                }
            }
        } catch (Exception e) {
            if (Constant.DEBUG) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 绘制天空层
     * @param g
     * @param x
     * @param y
     * @param w
     * @param h
     */
    private int iDrawCounter = 1;
    private int iAniindex = 0;

    public void drawSky(Graphics g, int x, int y, int w, int h) {
        try {
            int viewportX, viewportY;
            Image img = null;
            viewportY = y;
            viewportX = x;//this.iMapAnchorX + this.iMapViewOffsetX;
//            Tools.printLog("iMapViewOffsetX   :::  " + iMapViewOffsetX);
//            Tools.printLog("iMapViewOffsetY   :::  " + iMapViewOffsetY);
//            Tools.printLog("iMapWorldOffsetX   :::  " + iMapWorldOffsetX);
//            Tools.printLog("iMapWorldOffsetY   :::  " + iMapWorldOffsetY);
            //绘制第三层大图层
            int length = this.iMapData[3].length - 6;
            for (int i = length; i >= 0; i -= 6) {
                img = (Image) ResManager.getImage(this.iMapData[3][i], (byte) -1);
                if (img != null) {
                    if (this.iMapData[3][i + 1] + img.getWidth() >= iMapWorldOffsetX
                            && this.iMapData[3][i + 1] <= iMapWorldOffsetX + Constant.SCREEN_WIDTH
                            && this.iMapData[3][i + 2] + img.getHeight() >= iMapWorldOffsetY
                            && this.iMapData[3][i + 2] <= iMapWorldOffsetY + Constant.SCREEN_HEIGHT) {
                        Tools.drawRegion(img, 0, 0, img.getWidth(), img.getHeight(), this.iMapData[3][i + 5], this.iMapData[3][i + 1] - viewportX, this.iMapData[3][i + 2] - viewportY, 20, g);
                    }
                }
            }
            if (this.iDrawCounter == 0) {
                this.iDrawCounter++;
                iAniindex = 0;
            } else if (this.iDrawCounter == 2) {
                this.iDrawCounter++;
                iAniindex = 1;
            } else if (this.iDrawCounter == 4) {
                this.iDrawCounter++;
                iAniindex = 2;
            } else if (this.iDrawCounter >= 6) {
                this.iDrawCounter = 0;
            } else {
                this.iDrawCounter++;
            }
//  this.iDrawCounter++;

            //int length = this.iMapData[2].length - 6;
//            length = this.iMapData[4].length - 6;
//            for (int i = length; i >= 0; i -= 6) {
//                {
//                    if (this.iMapData[4][i + 3] != 0) {
//                        img = ResManager.getImage(this.iMapData[4][i + (this.iAniindex == 0 ? 0 : (this.iAniindex + 2))], (byte) -1);
//                    } else {
//                        img = ResManager.getImage(this.iMapData[4][i], (byte) -1);
//                    }
//                    if (img != null) {
//                        if (this.iMapData[4][i + 5] == 0) {
//                            if (this.iMapData[4][i + 1] + img.getWidth() >= iMapWorldOffsetX
//                                    && this.iMapData[4][i + 1] <= iMapWorldOffsetX + Constant.SCREEN_WIDTH
//                                    && this.iMapData[4][i + 2] + img.getHeight() >= iMapWorldOffsetY
//                                    && this.iMapData[4][i + 2] <= iMapWorldOffsetY + Constant.SCREEN_HEIGHT) {
//                                g.drawImage(img, this.iMapData[4][i + 1] - viewportX, this.iMapData[4][i + 2] - viewportY, 20);
//                            }
//                        } else {
//                            if (this.iMapData[4][i + 1] + 16 >= iMapWorldOffsetX
//                                    && this.iMapData[4][i + 1] <= iMapWorldOffsetX + Constant.SCREEN_WIDTH
//                                    && this.iMapData[4][i + 2] + 16 >= iMapWorldOffsetY
//                                    && this.iMapData[4][i + 2] <= iMapWorldOffsetY + Constant.SCREEN_HEIGHT) {
//                                Tools.drawRegion(img, 0, 0, 16, 16, this.iMapData[4][i + 5], this.iMapData[4][i + 1] - viewportX, this.iMapData[4][i + 2] - viewportY, 20, g);
//                            }
//                        }
//
//                    }
//                }
//            }
        } catch (Exception e) {
            if (Constant.DEBUG) {
                e.printStackTrace();
            }
        }
    }

    //当人物坐标更新的时候更新地图绘制的xys
    public boolean updateMayViewXy(int x, int y, int playerX, int playerY) {
//        this.iMapViewOffsetX += x;
//        this.iMapViewOffsetY += y;
        return updateMapXY(x, y, playerX, playerY);
    }

    public void updateMapXy(int x, int y) {
//        if (MainLogic.getInstance().gamePlayer != null) {
//            switch (MainLogic.getInstance().gamePlayer.byPlayerDirection) {
//                case Constant.PLAYER_DIRECTION_UP:
//                    this.iMapViewOffsetY = -(this.shAreaH - Constant.SCREEN_HEIGHT - Constant.TITLEWIDHT);
////                    }
//                    break;
//                case Constant.PLAYER_DIRECTION_DOWN:
//                    this.iMapViewOffsetY = 0;
//                    break;
//                case Constant.PLAYER_DIRECTION_LEFT:
//                    this.iMapViewOffsetX = (this.shAreaW - Constant.SCREEN_WIDTH - Constant.TITLEWIDHT);//-Constant.TITLEWIDHT;
//                    break;
//                case Constant.PLAYER_DIRECTION_RIGHT:
//                    this.iMapViewOffsetX = 0;//-Constant.TITLEWIDHT;
//                    break;
//            }
//        }
        this.iMapAnchorX = x;
        this.iMapAnchorY = y;
//        this.shMapAnchorR = (short) (x / this.byTileW);
//        this.shMapAnchorC = (short) (y / this.byTileH);
//        this.initOffSetXY(MainLogic.getInstance().gamePlayer.iPlayerX,MainLogic.getInstance().gamePlayer.iPlayerY);
//        this.iMapWorldOffsetX = this.iMapAnchorX + this.iMapViewOffsetX;
//        this.iMapWorldOffsetY = this.iMapAnchorY + this.iMapViewOffsetY;
    }

    public void initOffSetXY(int playerx, int playery) {
        this.iMapViewOffsetX = playerx - this.iMapAnchorX;
        this.iMapViewOffsetY = playery - this.iMapAnchorY;
        if ((this.iMapViewOffsetX + Constant.PLAYER_DISTANCE_SCREEN_X) > shAreaW) {
            this.iMapViewOffsetX = shAreaW - Constant.SCREEN_WIDTH;
        } else if (this.iMapViewOffsetX > Constant.PLAYER_DISTANCE_SCREEN_X) {
            this.iMapViewOffsetX -= Constant.PLAYER_DISTANCE_SCREEN_X;
        } else {
            this.iMapViewOffsetX = 0;
        }

        if ((this.iMapViewOffsetY + Constant.PLAYER_DISTANCE_SCREEN_Y) > this.shAreaH) {
            this.iMapViewOffsetY = this.shAreaH - Constant.SCREEN_HEIGHT;
        } else if (this.iMapViewOffsetY > Constant.PLAYER_DISTANCE_SCREEN_Y) {
            this.iMapViewOffsetY -= Constant.PLAYER_DISTANCE_SCREEN_Y;
        } else {
            this.iMapViewOffsetY = 0;
        }
        this.iMapWorldOffsetX = this.iMapAnchorX + this.iMapViewOffsetX;
        this.iMapWorldOffsetY = this.iMapAnchorY + this.iMapViewOffsetY;
    }
    public byte canNotGo(int x, int y, byte direct) {
//        int posx = 0;
//        int posy = 0;
//        switch(direct)
//        {
//            case Constant.PLAYER_DIRECTION_DOWN:
//                
//            break;
//           case Constant.PLAYER_DIRECTION_RIGHT:
//              if((x - this.iMapAnchorX)%16 == 0)
//           break;
//        }
//        int i = 9<<2;/
        this.shMapPlayerR = (short) (((x - this.iMapAnchorX) >> 4));
        this.shMapPlayerC = (short) (((y - this.iMapAnchorY) >> 4));
        try {
            if (x + 32 >= iAreaStartx + shAreaW || x - 32 <= iAreaStartx || y + 32 >= iAreaStarty + shAreaH || y - 32 <= iAreaStarty) {
                return 1;
            } else if (this.byCollisionData[this.shMapPlayerC][this.shMapPlayerR] == 1) {
                return 1;
            } else if (this.byCollisionData[this.shMapPlayerC][this.shMapPlayerR] == 2) {
                return 2;
            }
            //到达边界后返回
        } catch (Exception e) {
            if (Constant.DEBUG) {
                e.printStackTrace();
            }
        }
        return 0;
    }
    /*
    玩家走路更新xy坐标
     */

    public boolean updateMapXY(int x, int y, int playerX, int playerY) {
        this.iMapViewOffsetX += x;
        this.iMapViewOffsetY += y;
        boolean blChangex = true;
        boolean blChangey = true;
//        if (this.iMapViewOffsetX <= 0 || playerX - this.iMapAnchorX < Constant.PLAYER_DISTANCE_SCREEN_X) {
        if (playerX - this.iMapAnchorX < Constant.PLAYER_DISTANCE_SCREEN_X) {
//            Tools.printLog("this.iMapViewOffsetX = 0"+this.iMapViewOffsetX);
            this.iMapViewOffsetX = 0;
            blChangex = false;
        } else {
            if (shAreaW - (playerX - this.iMapAnchorX) <= Constant.PLAYER_DISTANCE_SCREEN_X) {
//              Tools.printLog("this.iMapViewOffsetX = shAreaW - Constant.SCREEN_WIDTH;"+this.iMapViewOffsetX);
                this.iMapViewOffsetX = shAreaW - Constant.SCREEN_WIDTH;

                blChangex = false;
            }
        }
        if (this.iMapViewOffsetY <= 0 || playerY - this.iMapAnchorY < Constant.PLAYER_DISTANCE_SCREEN_Y) {
            this.iMapViewOffsetY = 0;
            blChangey = false;
        } else {
//            if (y + Constant.SCREEN_HEIGHT >= (this.shAreaH +pos)|| this.shAreaH  - (playerY - this.iMapAnchorY) < Constant.PLAYER_DISTANCE_SCREEN_Y) {
            if ((this.shAreaH - this.iMapViewOffsetY < Constant.SCREEN_HEIGHT) || this.shAreaH - (playerY - this.iMapAnchorY) < Constant.PLAYER_DISTANCE_SCREEN_Y) {
                this.iMapViewOffsetY = this.shAreaH - Constant.SCREEN_HEIGHT;
                blChangey = false;
            }
        }
        //#if NOKIA_S40V3 ||NOKIAN73 || NORMAL_240_400 || MOTO || K790
//# //        if ((x != 0 && blChangex) || (y != 0 && blChangey))
//#         {
//#             scroll(x, y);
//#         }
        //#else
        //#endif
        //更新地图

//        if (blChangey) {
        this.iMapWorldOffsetY = this.iMapAnchorY + this.iMapViewOffsetY;
//        }
//        if (blChangex) {
        this.iMapWorldOffsetX = this.iMapAnchorX + this.iMapViewOffsetX;
//        }
        //边界判断
        if ((playerX < this.iMapAnchorX) || (playerX > this.iMapAnchorX + shAreaW) || (playerY < this.iMapAnchorY) || (playerY > this.iMapAnchorY + this.shAreaH)) {
            if (MainLogic.blLogined) {
                return true;
            }
        }
        return false;
    }
    /**
     * 是否达到边界达到边界发指令
     * @return
     */
    private static int[] iMapArray = {
        1
    };
    //判断是否在本地

    public static boolean getLocalMapId(int mapid) {
        for (int i = iMapArray.length - 1; i >= 0; i--) {
            if (mapid == iMapArray[i]) {
                return true;
            }
        }
        return false;
    }

    public ByteArrayOutputStream saveMap() {
        try {
            ByteArrayOutputStream streamData = new ByteArrayOutputStream();
            DataOutputStream dataIS = new DataOutputStream(streamData);
            //起始点坐标
            dataIS.writeInt(iMapAnchorX); //int istartX = streamIn.readInt();
            dataIS.writeInt(iMapAnchorY); // int istarty = streamIn.readInt();
            //关卡宽高
            dataIS.writeInt(shAreaW); //this.shAreaW = streamIn.readUnsignedShort();
            dataIS.writeInt(shAreaH); //this.shAreaH = streamIn.readUnsignedShort();
            dataIS.writeInt(ilayer0TileCount);// int ilayer0TileCount = streamIn.readUnsignedShort();
            for (int i = 0; i < ilayer0TileCount; i++) {
                dataIS.writeInt(iMapData[0][i]);
                dataIS.writeInt(iMapData[0][i + 1]);
                dataIS.writeInt(iMapData[0][i + 1]);
            }
//            iMapData[0][j] = m_resId;
//                    iMapData[0][j + 1] = m_posX;
//                    iMapData[0][j + 2] = m_posY;
//                    iMapData[0][j + 3] = m_resId2;
//                    iMapData[0][j + 4] = m_resId3;
//                    iMapData[0][j + 5] = m_rot;
//              m_resId = streamIn.readUnsignedShort();
////                 System.out.print("" +m_resId);
//                m_posX = streamIn.readInt();
//                m_posY = streamIn.readInt();
//                m_rot = streamIn.readUnsignedByte();
//                m_resId2 = streamIn.readUnsignedShort();
//                m_resId3 = streamIn.readUnsignedShort();
            dataIS.writeInt(ilayer1TileCount);// int ilayer1TileCount = streamIn.readUnsignedShort();
            dataIS.writeInt(ilayer2TileCount);// int ilayer2TileCount = streamIn.readUnsignedShort();
            dataIS.writeInt(ilayer3TileCount);// int ilayer3TileCount = streamIn.readUnsignedShort();
            dataIS.writeInt(ilayer4TileCount);// int ilayer4TileCount = streamIn.readUnsignedShort();
            dataIS.writeInt(iborderTileCount);//   //边界：上下左右角 上下左右边 int iborderTileCount = streamIn.readUnsignedShort();
            //更新区域地图坐标MainLogic.gameMap.iMapWorldOffsetX, MainLogic.gameMap.iMapWorldOffsetY
            dataIS.writeInt(iblockXCount);//iblockXCount = streamIn.readUnsignedShort();
            //占地各自行数0 --- 可走  1--- 不可走  2 --- 转换（待定）
            dataIS.writeInt(iblockYCount);// iblockYCount = streamIn.readUnsignedShort();
            for (int i = 0; i < iblockYCount; i++) {
                for (int k = 0; k < iblockXCount; k++) {
                    dataIS.writeByte(this.byCollisionData[i][k]); //  = streamIn.readByte();
                }
            }
            dataIS.writeInt(iblockYCount);// iblockYCount = streamIn.readUnsignedShort();
            for (int i = 0; i < iblockYCount; i++) {
                for (int k = 0; k < iblockXCount; k++) {
                    dataIS.writeByte(this.byCollisionData[i][k]); //  = streamIn.readByte();
                }
            }
            dataIS.close();
            return streamData;
        } catch (Exception e) {
            if (Constant.DEBUG) {
                e.printStackTrace();
            }
        }
        return null;
    }
    //////////////////////////测试卡马克//////////////////
    /**
     * 设置地图片数据
     *
     * @param image
     *            地图图片
     * @param map
     *            地图的二维数组
     */
}
